package com.gl.order.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gl.order.commom.ResultBean;
import com.gl.order.commom.util.ProcessCommonUtil;
import com.gl.order.commom.util.WordUtils;
import com.gl.order.entity.CustomerInfo;
import com.gl.order.entity.TOrder;
import com.gl.order.entity.TUser;
import com.gl.order.entity.dto.*;
import com.gl.order.entity.dto.DeliverPageDto;
import com.gl.order.entity.vo.DeliverPageVo;
import com.gl.order.entity.vo.OrderInfoVo;
import com.gl.order.entity.vo.OrderPageVo;
import com.gl.order.entity.vo.PeripheralProductsVo;
import com.gl.order.security.model.SecurityUser;
import com.gl.order.service.CustomerService;
import com.gl.order.service.OrderService;
import com.gl.order.service.ProcessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @Author: liangSY
 * @Date: 2021/6/26
 * @ClassName: OrderController
 * @Description: 订单管理
 */
@Api(tags = "订单管理")
@RestController
@RequestMapping("/orders")
public class OrderController {

    private OrderService orderService;

    private ProcessService processService;

    private CustomerService customerService;

    public OrderController(OrderService orderService, ProcessService processService, CustomerService customerService) {
        this.orderService = orderService;
        this.processService = processService;
        this.customerService = customerService;
    }

    @PostMapping("/order/pages")
    @ApiOperation("获取订单列表")
    public ResultBean<IPage<OrderPageVo>> list(@RequestBody @Valid OrderPageDto dto) {
        List<String> createTime = dto.getCreateTime();
        if (null != createTime && !createTime.isEmpty()) {
            dto.setCreateTimeStart(createTime.get(0));
            dto.setCreateTimeEnd(createTime.get(1));
        }
        SecurityUser SecurityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        TUser user = SecurityUser.getCurrentUserInfo();
        for (String role : SecurityUser.getPermissionsList()) {
            if ("customer_service".equals(role)) {
                dto.setServiceName(user.getId());
            }
            if ("market".equals(role)) {
                dto.setMarket(user.getId());
            }
        }
        return ResultBean.success(orderService.pageList(dto));
    }

    @PostMapping("/order/deliverPages")
    @ApiOperation("获取订单快递信息列表")
    public ResultBean<IPage<DeliverPageVo>> deliverList(@RequestBody @Valid DeliverPageDto dto) {
        return ResultBean.success(orderService.pageList(dto));
    }

    @PostMapping("/order/peripheralProductsPages")
    @ApiOperation("获取周边产品信息列表")
    public ResultBean<IPage<PeripheralProductsVo>> peripheralProductsList(@RequestBody @Valid PeripheralProductsPageDto dto) {
        List<String> shipmentTime = dto.getShipmentTime();
        if (null != shipmentTime && !shipmentTime.isEmpty()) {
            dto.setShipmentTimeStart(shipmentTime.get(0));
            dto.setShipmentTimeEnd(shipmentTime.get(1));
        }
        return ResultBean.success(orderService.pageList(dto));
    }

    @PostMapping("/saveOrderInfo")
    @ApiOperation("修改订单基本信息")
    public ResultBean saveOrderInfo(@RequestBody TOrder order) {
        orderService.updateById(order);
        return ResultBean.success();
    }

    private ResultBean startProcess(String orderId, TOrder order) {
        try {
            String jdwid = ProcessCommonUtil.START_PROCESS;
            String czlx = ProcessCommonUtil.CZLX_AUDIT;
            Map<String, Object> param = ProcessCommonUtil.auditProcessMap("t_order", orderId, "1", jdwid, czlx);
            processService.auditProcess(param);
            return ResultBean.success(order);
        } catch (Throwable throwable) {
            throwable.getMessage();
            return ResultBean.failed(throwable.getMessage());
        }
    }

    @GetMapping("/orderCreate/start")
    @ApiOperation("开始流程")
    public ResultBean start(String orderId) {
        return startProcess(orderId, null);
    }

    @PostMapping("/orderCreate/add")
    @ApiOperation("添加订单")
    public ResultBean add(@RequestBody @Valid OrderDto dto) throws Throwable {
        TOrder order = orderService.add(dto);
        return startProcess(order.getId(), order);
    }

    @PostMapping("/orderCreate/addPeripheralProducts")
    @ApiOperation("添加周边产品订单")
    public ResultBean addPeripheralProducts(@RequestBody @Valid OrderDto dto) {
        TOrder order = orderService.add(dto);
        return ResultBean.success(order);
    }

    @PostMapping("/orderCreate/edit")
    @ApiOperation("修改订单")
    public ResultBean edit(@RequestBody @Valid UpdateOrderDto dto) {
        orderService.editOrder(dto);
        // 更新客户的修改时间
        if (StringUtils.isNotBlank(dto.getCustomerId())) {
            CustomerInfo customerInfo = new CustomerInfo();
            customerInfo.setUpdateTime(LocalDateTime.now());
            customerInfo.setId(dto.getCustomerId());
            customerService.updateById(customerInfo);
        }
        return ResultBean.success();
    }

    @PostMapping("/orderCreate/copy")
    @ApiOperation("加单")
    public ResultBean copy(@RequestBody @Valid OrderCopyDto dto){
        orderService.copy(dto);
        return ResultBean.success();
    }

    @PostMapping("/saveImage")
    @ApiOperation("保存图片")
    public ResultBean saveImage(@RequestParam(value = "sampleImgs", required = false) List<MultipartFile> sampleImgs,
                          @RequestParam(value = "payImgs", required = false) List<MultipartFile> payImgs, String orderNo, String orderId){
        orderService.saveImg(sampleImgs, payImgs, orderId, orderNo);
        return ResultBean.success();
    }

    @GetMapping("/orderCreate/info")
    @ApiOperation("获取订单详情")
    public ResultBean<OrderInfoVo> getOrder(@RequestParam("id") String id){
        return ResultBean.success(orderService.getOrderInfo(id));
    }

    @DeleteMapping("/delete/del")
    @ApiOperation("删除订单")
    public ResultBean del(@RequestParam("id") String id){
        orderService.delOrder(id);
        return ResultBean.success();
    }

    @PostMapping("/delete/delIds")
    @ApiOperation("删除订单")
    public ResultBean del(@RequestBody OrderDelDto dto){
        orderService.delOrders(dto.getIds());
        return ResultBean.success();
    }

    @GetMapping("/orderCreate/isCreate")
    @ApiOperation("判断是否拥有创建订单的权限")
    public ResultBean isCreate(){
        return ResultBean.success();
    }

    @PostMapping("/excel/export")
    @ApiOperation("导出订单")
    public void excelExport(HttpServletResponse response, @RequestBody OrderExcelDto dto) throws IOException {
        orderService.excelExport(response,dto);
    }

    @GetMapping("/doc/export")
    @ApiOperation("导出订单")
    public void docExport(HttpServletResponse response, HttpServletRequest request,@RequestParam("id") String id) throws IOException {
        Map<String,Object> data = orderService.getWordData(id);
        WordUtils.export(request,response,data,"订单","order_template_current.ftl");
    }

}
